import { build, calculate, create, payment, check_shipping } from "../../../api/order"
import {
  submit,
  query
} from '../../../api/payment';
import {
  list
} from '../../../api/address';
import { find } from '../../../api/shop'
const util = require('../../../utils/util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    distributionType: true,
    quantity: 0,
    address: null,
    calculate: null,
    couponCodeName: '',
    couponsType: false,
    discountTotal: 0,
    amount: 0,
    memo: '点击可选择无接触配送',
    tablewareTitle: '无需餐具',
    shopPhone: "请填写手机号",
    shopId: '',
    shopForm: null,
    shippingMethods: [],
    shippingMethodType: false,
    orderId: null,
    sn: '',
    shippingMethod: '2',
    showDate:"",
    estimateDate: '',
    estimateTime: '',
    shippingConfig:{},
    nowType:false,
    workBeginTime:'00:00:00',
    workEndTime:'23:59:59',
    canShippingmake:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.shopId = options.shopId
    this.loadShop()
    this.buildClick(options.shopId)
  },
  chooseLeftClick() {
    var _this = this
    this.data.distributionType = true
    _this.data.shippingMethod = 2
    _this.data.calculate.shippingMethod = 2
    _this.calculateClick(_this.data.calculate)
    this.setData({
      distributionType: this.data.distributionType
    })
  },
  chooseRightClick() {
    var _this = this
    this.data.distributionType = false
    _this.data.shippingMethod = 1
    _this.data.calculate.shippingMethod = 1
    _this.calculateClick(_this.data.calculate)
    this.setData({
      distributionType: this.data.distributionType
    })
  },
  reduceClick() {
    if (this.data.quantity > 0) {
      this.data.quantity -= 1
      this.setData({
        quantity: this.data.quantity
      })
    }
  },
  addClick() {
    this.data.quantity += 1
    this.setData({
      quantity: this.data.quantity
    })
  },
  successClick() {
    var _this = this
    console.log('我进来了')
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    _this.data.calculate.shopId = _this.data.shopId
    if (_this.data.distributionType == true) {
      if (_this.data.address == null) {
        wx.hideLoading()
        wx.showToast({
          title: '请选择地址',
        })
      } else {
        _this.data.shippingMethod = 2
        _this.data.calculate.shippingMethod = 2
        _this.checkClick()
      }
    } else if (_this.data.distributionType == false) {
      if (_this.data.shopPhone == '' || _this.data.shopPhone == '请填写手机号') {
        wx.hideLoading()
        wx.showToast({
          title: '请填写电话',
        })
      } else {
        _this.data.shippingMethod = 1
        _this.data.calculate.shippingMethod = 1
        _this.checkClick()
      }
    }
  },

  checkClick() {
    var _this = this
    check_shipping(_this.data.calculate, {
      receiverId: _this.data.calculate.receiverId
    }).then(
      res => {
        console.log(res)
        if (res.data.length == 0) {
          _this.createClick()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '您已经超出配送范围',
          })
        }
      }
    ).catch(error => {
      console.info("error---------------------------")
      console.info(error)
      
      wx.hideLoading()
      wx.showToast({title:error.content,icon:"none"})
    })
  },

  // 获取购物车商品
  buildClick(shopId) {
    var _this = this
    let params = {
      shopId:shopId
    }
    build(params).then(res => {
      console.log(res)
      _this.data.calculate = res.data.order
      if(!util.isNull(res.data.shippingConfig)){
        _this.data.shippingConfig = JSON.parse(res.data.shippingConfig)
        _this.workDate()
      }
      if(_this.data.shippingConfig.shippingmake>0){
        _this.data.canShippingmake = true
      }
      console.log('预约时间')
      console.log(_this.data.shippingConfig)
      _this.loadList()
      if (!util.isNull(res.data.shippingMethods)) {
        _this.data.shippingMethods = res.data.shippingMethods.split(",")
        _this.data.shippingMethods.forEach(function (item) {
          if (_this.data.shippingMethods.length > 1 && item == 1) {
            _this.data.shippingMethodType = true
          }
          if (_this.data.shippingMethods.length == 1 && item == 1) {
            _this.data.distributionType = false
          }
        })
      }
      _this.setData({
        calculate: _this.data.calculate,
        shippingMethodType: _this.data.shippingMethodType,
        distributionType: _this.data.distributionType,
        shippingConfig:_this.data.shippingConfig,
        canShippingmake:_this.data.canShippingmake
      })
    })
  },
  // 获取默认地址
  loadList() {
    var _this = this
    var defaultAddress = []
    list({
      mchId: app.globalData.mchId
    }).then(res => {
      console.log(res)
      if (res.data.data.length > 0) {
        res.data.data.forEach(function (item) {
          if (item.isDefault == true) {
            defaultAddress.push(item)
          }
        })
      }
      if (!util.isNull(defaultAddress)) {
        _this.data.address = defaultAddress[0]
      }
      console.log(_this.data.address)
      console.log('默认地址')
      if (this.data.address != null) {
        _this.data.calculate.address = _this.data.address.address
        _this.data.calculate.receiverId = _this.data.address.id
        _this.data.calculate.areaName = _this.data.address.areaName
        _this.data.calculate.consignee = _this.data.address.consignee
        _this.data.calculate.phone = _this.data.address.phone
      }
      _this.setData({
        address: _this.data.address,
        calculate: _this.data.calculate
      })
      _this.calculateClick(_this.data.calculate)
    }).catch(error => {
    })
  },
  calculateClick(data) {
    var _this = this
    calculate(data).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          res.data.order.itemList.forEach(function (item) {
            item.thumbnail = util.thumbnail(item.thumbnail, 115, 115)
          })
          res.data.order.amountPayable = (Number(res.data.order.amountPayable)).toFixed(2)
          this.data.calculate = res.data.order
          this.data.discountTotal = (Number(res.data.order.discount) + Number(res.data.order.couponDiscount)).toFixed(2)
          this.data.amount = res.data.amount.toFixed(2)
          if (!util.isNull(res.data.couponCodeName)) {
            _this.data.couponCodeName = res.data.couponCodeName
            _this.setData({
              couponCodeName: _this.data.couponCodeName
            })
          }
          this.setData({
            calculate: this.data.calculate,
            discountTotal: this.data.discountTotal,
            amount: this.data.amount
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  // 优惠列表弹窗
  cenclecoupons() {
    this.data.couponsType = false
    this.setData({
      couponsType: this.data.couponsType
    })
  },
  completecoupons: function (e) {
    console.log(e)
    this.data.couponsType = false
    this.setData({
      coupons: e.detail.completecoupons,
      couponsType: this.data.couponsType
    })
  },
  couponsClick() {
    if (this.data.calculate.discount == 0 && this.data.calculate.couponDiscount == 0) {
      wx.showToast({
        title: '暂无优惠',
        icon: "none",
      })
    } else {
      this.data.couponsType = true
      this.setData({
        couponsType: this.data.couponsType
      })
    }
  },
  // 选择支付方式
  changeClick(data) {
    console.log(data)
    var _this = this
    var paymentPluginId = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].paymentPluginId
    if (_this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk == false) {
      if (_this.data.amount != 0) {
        if (paymentPluginId == 'waterTicketPayPlugin' || paymentPluginId == 'couponCodePayPlugin') {
          var amount = 0
          _this.data.calculate.paymentVo.forEach(function (item) {
            amount += Number(item.amount)
            item.amount = 0
            item.chk = false
          })
          amount = Number(amount) + Number(_this.data.amount)
          console.log(amount)
          console.log(_this.data.calculate.paymentVo)
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = true
          _this.data.amount = amount - _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount
        } else {
          if (_this.data.amount >= _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance) {
            _this.data.amount = (Number(_this.data.amount) - Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance)).toFixed(2)
            _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance
          } else {
            _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.amount
            _this.data.amount = 0
          }
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = true
        }
      } else {
        _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = false;
        wx.showToast({
          icon: "none",
          title: '本商品已无法抵用优惠',
        })
      }
    } else {
      _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = false
      _this.data.amount = Number(_this.data.amount) + Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount)
      console.log(_this.data.amount)
      _this.data.amount = _this.data.amount.toFixed(2)
      _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = 0
    }
    _this.setData({
      calculate: _this.data.calculate,
      amount: _this.data.amount
    })
  },
  // 备注
  savedialogClick(e) {
    console.log(e)
    this.data.calculate.memo = e.detail
    this.data.memo = e.detail
    this.setData({
      calculate: this.data.calculate,
      memo: this.data.memo
    })
  },
  dialogClick() {
    this.selectComponent('#dialog').appear()
  },
  // 餐具选择
  tablewareClick() {
    this.selectComponent('#tableware').typeClick()
  },
  saveTableware(data) {
    console.log(data)
    console.log('我选择了餐具')
    this.data.tablewareTitle = data.detail.title
    if (data.detail.index > 0) {
      this.data.calculate.tableware = data.detail.index
    } else {
      this.data.calculate.tablewar = ''
    }
    this.setData({
      tablewareTitle: this.data.tablewareTitle,
      calculate: this.data.calculate
    })
  },
  // 手机号弹窗
  savedialogPhoneClick(e) {
    console.log(e)
    this.data.shopPhone = e.detail
    this.setData({
      shopPhone: this.data.shopPhone
    })
  },
  dialogPhoneClick() {
    this.selectComponent('#dialogPhone').appear()
  },
  loadShop() {
    var _this = this
    find(this.data.shopId).then(res => {
      _this.data.shopForm = res.data.shop
      _this.setData({
        shopForm: _this.data.shopForm
      })
    })
  },
  // 点击切换地址
  addressClick() {
    var _this = this
    wx.navigateTo({
      url: '/pages/member/address/address?type=product',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
          _this.data.address = data.data
          _this.data.calculate.address = _this.data.address.address
          _this.data.calculate.receiverId = _this.data.address.id
          _this.data.calculate.areaName = _this.data.address.areaName
          _this.data.calculate.consignee = _this.data.address.consignee
          _this.data.calculate.phone = _this.data.address.phone
          _this.setData({
            address: _this.data.address,
            calculate: _this.data.calculate
          })
          _this.calculateClick(_this.data.calculate)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
    })
  },
  // 创建订单
  createClick() {
    var _this = this
    console.log('创建订单')
    _this.data.calculate.estimateDate = _this.data.estimateTime
    if (this.data.distributionType == false) {
      _this.data.calculate.phone = _this.data.shopPhone
    }
    let sendData = JSON.stringify(_this.data.calculate)
    create(sendData, {
      shippingMethod: _this.data.shippingMethod,
    }).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          _this.data.orderId = res.data.id
          if (res.data.paymentStatus == 1) {
            wx.hideLoading()
            wx.redirectTo({
              url: '/pages/shop/settlement/success?id=' + _this.data.orderId,
            })
          } else {
            _this.paymentClick(res)
          }
        }
      }
    ).catch(error => {
      console.log('我出错了')
      console.log(error)
      wx.hideLoading()
      wx.showToast({
        title: error.content,
        icon:'error'
      })
      
    })
  },
  paymentClick(data) {
    var _this = this
    payment(data.data.id).then(res => {
      if (res.type == 'success') {
        _this.submitClick(res)
      } else {
        wx.hideLoading()
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.hideLoading()
    })
  },
  submitClick(data) {
    var _this = this
    _this.data.sn = data.data.sn
    submit({
      paymentPluginId: 'weixinMiniPayPlugin',
      sn: data.data.sn
    }).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.type == 'success') {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (red) {
            setTimeout(function(){
              _this.queryClick()
            }, 100);
          },
          'fail': function (red) {
            wx.showToast({
              icon: "none",
              title: '支付失败',
            })
            wx.redirectTo({
              url: '/pages/order/order/details?id=' + _this.data.orderId,
            })
          }
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: '支付失败',
      })
      wx.redirectTo({
        url: '/pages/order/order/details?id=' + _this.data.orderId,
      })
    })
  },
  queryClick() {
    var _this = this
    query({
      sn: _this.data.sn
    }).then(res => {
      console.log(res)
      if (res.type == 'success') {
        wx.redirectTo({
          url: '/pages/shop/settlement/success?id=' + _this.data.orderId,
        })
      }
    }).catch(error => {
      wx.redirectTo({
        url: '/pages/shop/settlement/success?id=' + _this.data.orderId,
      })
    })
  },
  // 选取时间
  myevent(data) {
    console.log(data)
    console.log('获取到时间了')
    var _this = this
    let selectDate = data.detail.date.replace(/-/g,"/")
    _this.data.showDate = data.detail.date
    _this.data.estimateDate = data.detail.startTime
    _this.data.estimateTime = Date.parse(selectDate + ' ' + data.detail.startTime + ":00");
    _this.setData({
      showDate: _this.data.showDate,
      estimateDate: _this.data.estimateDate,
      estimateTime: _this.data.estimateTime
    })

    console.log(this.data.estimateDate)
    console.log(this.data.estimateTime)
  },
  deliveryTimeClick() {
    this.selectComponent('#deliveryTime').deliveryTimeClick()
  },
  nowTypeClick(data){
    console.log(data)
    this.data.nowType = data.detail
    this.setData({
      nowType:this.data.nowType
    })
    console.log('现在是否开业')
  },
  workDate(){
    var _this = this
    if(!util.isNull(_this.data.shippingConfig.workBeginTime)){
      _this.data.workBeginTime = _this.data.shippingConfig.workBeginTime
      _this.setData({
        workBeginTime:_this.data.workBeginTime
      })
    }
    if(!util.isNull(_this.data.shippingConfig.workEndTime)){
      _this.data.workEndTime = _this.data.shippingConfig.workEndTime
      _this.setData({
        workEndTime:_this.data.workEndTime
      })
    }
  }
})
